//
//  SurveyDetailViewController.m
//  homeland
//
//  Created by SunShine on 13-10-20.
//  Copyright (c) 2013年 xzysun. All rights reserved.
//  民情调查详情展示类
//

#import "SurveyDetailViewController.h"
#import "UIImageView+WebCache.h"
#import "SurveyMasterEntity.h"
#import "SurveyItemEntity.h"
#import "UserInfoService.h"
#import "CheckButton.h"
#import "RadioGroup.h"
#import <QuartzCore/QuartzCore.h>
//扩展属性
@interface SurveyDetailViewController ()
//变量区
//=========================
//定义一个变量来记录下一个将要添加的控件的位置
@property (assign, nonatomic) int nextY;
//调查主体id
@property (strong, nonatomic) NSString *masterId;
//获取的调查项结果集
@property (strong, nonatomic) NSDictionary *jsonData;
//是否投过票
@property (assign, nonatomic) NSInteger countNum;
//是否结束
@property (assign, nonatomic) NSInteger isEnd;
//存储单选投票结果：key是题目id,value是选中的条目id
@property (strong, nonatomic) NSMutableDictionary *rResultDic;
//存储复选投票结果：key是题目id,value是选中的条目id集（一个或多个）
@property (strong, nonatomic) NSMutableDictionary *cResultDic;
@end

@implementation SurveyDetailViewController
//唯一静态变量key－用于关联函数传参
static const char associatedkey;
//方法区
//=========================
-( id )initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self =[ super initWithNibName :nibNameOrNil bundle :nibBundleOrNil];
    if (self){
        
    }
    return self ;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"详情";
    [self configView];
}

/**数据渲染展示*/
-(void)configView{
    _nextY = 0;
    _rResultDic = [NSMutableDictionary dictionary];
    _cResultDic = [NSMutableDictionary dictionary];
  //主体内容展示
  //--------------------------
    SurveyMasterEntity *item = [_config objectForKey:@"dataItem"];
    _masterId = [CommonUtil dealNullObject:item.Id];
    //是否投过票，大于零表示投过
    _countNum = [CommonUtil dealNullObject:item.countNum].intValue;
    //是否结束，等于零表示过期
    _isEnd = (NSNull *)item.isEnd == [NSNull null] ?1:[CommonUtil dealNullObject:item.isEnd].intValue;
    //展示图片
    //--------------------
    //self.imageView.frame = CGRectMake(10.0, 10.0, 300.0, 200.0);
    NSString *pic = [NSString stringWithFormat:@"http://%@%@", SURVEY_PIC_BASE_URL, item.surveyImage];
    __block UIActivityIndicatorView *activityIndicator;
    __weak UIImageView *weakImageView = self.imageView;
    [self.imageView setImageWithURL:[NSURL URLWithString:pic] placeholderImage:[UIImage imageNamed:@"placeholder.png"] options:SDWebImageProgressiveDownload progress:^(NSUInteger receivedSize, long long expectedSize){
        if (!activityIndicator){
            [weakImageView addSubview:activityIndicator = [UIActivityIndicatorView.alloc initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]];
            activityIndicator.center = weakImageView.center;
            [activityIndicator startAnimating];
        }
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType){
        [activityIndicator removeFromSuperview];
        activityIndicator = nil;
    }];
    
    //展示主体内容
    //-------------------
    NSString *_Vtitle = [CommonUtil dealNullObject:item.surveyTitle];
    NSString *_Vcontent = [CommonUtil dealNullObject:item.surveyContext];
    //根据内容调整高度
    CGFloat titleHeight = [self caculateHeightForString:_Vtitle AndFontSize:16.0f AndWitdh:300.0f];
    CGFloat contentHeight = [self caculateHeightForString:_Vcontent AndFontSize:14.0f AndWitdh:300.0f];
    
    self.titleTextView.frame = CGRectMake(0.0,10.0, 300.0, titleHeight);
    self.titleTextView.text = _Vtitle;
    
    //间隔线
    self.spiritLine.frame = CGRectMake(10.0, CGRectGetMaxY(self.titleTextView.frame), 280.0, 1.0);
    
    self.contentTextView.frame = CGRectMake(0.0, CGRectGetMaxY(self.spiritLine.frame), 300.0, contentHeight);
    self.contentTextView.text = _Vcontent;
    
    self.timePanel.frame = CGRectMake(0.0, CGRectGetMaxY(self.contentTextView.frame) + 10.0, 300.0, 21.0);
    self.startDateLabel.text = [CommonUtil formatDateStr:item.startTime style:@"yyyy-MM-dd"];
    self.endDateLabel.text = [CommonUtil formatDateStr:item.endTime style:@"yyyy-MM-dd"];
   
    //设置内容区域高度及边框：
    self.contentPanel.frame = CGRectMake(10.0, CGRectGetMaxY(self.imageView.frame) + 10.0, 300.0, titleHeight + contentHeight + 50.5);
    //TODO——待处理边框范围问题
    //self.contentPanel.layer.borderColor = UIColor.grayColor.CGColor;
    //self.contentPanel.layer.borderWidth =1.0;
    
    _nextY+= (CGRectGetMaxY(self.contentPanel.frame) + 20.0);//下一元素显示的位置
    NSLog(@"下一元素的位置为：%d",_nextY);
    //调查选项内容展示
    //--------------------------
    [self getItemContent:item.Id];
}

/**获取调查选项数据并展示*/
- (void)getItemContent:(NSString *)surveyId{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    if ([params objectForKey:@"userId"]==nil) {
        [params setValue:userInfo.userInfo.Id forKey:@"userID"];
    }
    NSString *getDataUrl = [NSString stringWithFormat:@"%@/%@", SERVER_URL_SURVEY_INFO_LIST, surveyId];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:getDataUrl customHeaderFields:nil];
    //请求服务端数据
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:params httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        _jsonData = [completedOperation responseJSON];
        //处理数据展示
        [self createItemZone:_jsonData];
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        
    }];
    [currentEngine enqueueOperation:op];
}

/**创建调查项展示区域*/
- (void)createItemZone:(NSDictionary *)json{
    //转换对象
    int i=1;
    for(NSDictionary *nsd in json){
        //直接进行布局展示
        [self addItem:nsd itemNum:i];
        i++;
    }
    if(_countNum > 0){//已投过票
        //不做任何操作
    }else{//未投过票的则显示提交按钮
        //未投过票且已过期
        if(_isEnd==0){
            [self createBtn:@"end"];
        }else{
            [self createBtn:@"post"];
        }
    }
    
    CGFloat totalHeight = MAX(_nextY+10, CGRectGetHeight(self.scrollView.frame));
    self.mainPanel.frame = CGRectMake(0.0, 0.0, 320.0, totalHeight);
    [self.scrollView addSubview:self.mainPanel];
    self.scrollView.contentSize = self.mainPanel.frame.size;
}

/**新增元素视图*/
- (void)addItem:(NSDictionary *) nsd itemNum:(int) itemNum{
    SurveyItemEntity *tempEntity = [SurveyItemEntity alloc];
    tempEntity.Id = [nsd objectForKey:@"id"];
    tempEntity.surveyTwoItemList = [nsd objectForKey:@"surveyTwoItemList"];//二级选项
    
    NSLog(@"当前元素的位置为：%d",_nextY);
    if (itemNum >=1){//没有解决边框显示问题,暂时这样处理
        //分割线
        UITextView* spiritLine = [[UITextView alloc] initWithFrame:CGRectMake(10, _nextY, 300, 0.5)];
        spiritLine.backgroundColor = [UIColor blackColor];
        
        [self.mainPanel addSubview:spiritLine];
        
        _nextY += 10.5;//与下一元素的垂直间距为10.5
    }
    
    //标题
    //--------------
    UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(15, _nextY, 300, 30)];
    
    NSString * labelStr = [CommonUtil dealNullObject:[nsd objectForKey:@"surveyItemContext"]];
    labelStr = [[NSString stringWithFormat:@"%d、",itemNum] stringByAppendingString:labelStr];
    //300为UILabel的宽度，100是预设的一个高度，表示在这个范围内
    CGSize labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:14]
                                 constrainedToSize:CGSizeMake(300.0, 100)
                                 lineBreakMode:NSLineBreakByWordWrapping];
    label.font = [UIFont systemFontOfSize:14];//字体加粗、大小
    label.textAlignment = NSTextAlignmentLeft;//文字居左显示
    label.numberOfLines = 0;//表示label可以多行显示
    label.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
    label.frame = CGRectMake(label.frame.origin.x, label.frame.origin.y, label.frame.size.width, labelSize.height);//保持原来Label的位置和宽度，只是改变高度。
    
    label.text = labelStr;
    label.textColor = [UIColor orangeColor];
    [self.mainPanel addSubview:label];
    
    _nextY += 40+(labelSize.height-30);//与下一元素的垂直间距为40+
    
    //选项
    //--------------
    NSInteger isMulti = [CommonUtil dealNullObject:[nsd objectForKey:@"isMulti"]].intValue;
    if (isMulti==0) {//0表示多选模式
        for(NSDictionary *subNsd in tempEntity.surveyTwoItemList) {
            // 第 i 个复选按钮
            CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (20, _nextY , 260 , 32 )];
            NSString * labelStr = [CommonUtil dealNullObject:[subNsd objectForKey:@"twoItemContext"]];
            //300为UILabel的宽度，100是预设的一个高度，表示在这个范围内
            CGSize labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:13]
                                    constrainedToSize:CGSizeMake(300.0, 100)
                                        lineBreakMode:NSLineBreakByWordWrapping];
            cb.label.font = [UIFont systemFontOfSize:13];//字体大小
            cb.label.textAlignment = NSTextAlignmentLeft;//文字居左显示
            cb.label.numberOfLines = 0;//表示label可以多行显示
            cb.label.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
            cb.label.frame = CGRectMake(cb.label.frame.origin.x, cb.label.frame.origin.y, cb.label.frame.size.width, labelSize.height);//保持原来Label的位置和宽度，只是改变高度。
            
            cb.label.text = labelStr;

            cb.value = [CommonUtil dealNullObject:[subNsd objectForKey:@"id"]];
            // 把按钮设置为复选按钮样式
            cb. style = CheckButtonStyleBox ;
            //处理选中状态及可用状态
            NSInteger isCheck = [CommonUtil dealNullObject:[subNsd objectForKey:@"surveyResultID"]].intValue;
            if(isCheck > 0){//已选中
                cb.checked = YES;
            }
            if((_countNum > 0)||(_isEnd==0)){//已投过票或已结束
                cb.enabled = NO;
            }
            // 加入视图
            [self.mainPanel addSubview :cb];
            // 添加选择事件
            //使用关联函数方式传递参数
             objc_setAssociatedObject(cb, &associatedkey, tempEntity.Id, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [cb addTarget:self action:@selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            _nextY += 42;//与下一元素的垂直间距为42
        }
    }else{//1表示单选模式
        // 单选按钮组
        RadioGroup *rg =[[ RadioGroup alloc ] init ];
        for(NSDictionary *subNsd in tempEntity.surveyTwoItemList) {
            // 第 i 个单选按钮
            CheckButton * cb=[[ CheckButton alloc ] initWithFrame : CGRectMake (20, _nextY, 260, 32)];
            NSString * labelStr = [CommonUtil dealNullObject:[subNsd objectForKey:@"twoItemContext"]];
            //300为UILabel的宽度，100是预设的一个高度，表示在这个范围内
            CGSize labelSize = [labelStr sizeWithFont:[UIFont systemFontOfSize:13]
                                    constrainedToSize:CGSizeMake(300.0, 100)
                                        lineBreakMode:NSLineBreakByWordWrapping];
            cb.label.font = [UIFont systemFontOfSize:13];//字体大小
            cb.label.textAlignment = NSTextAlignmentLeft;//文字居左显示
            cb.label.numberOfLines = 0;//表示label可以多行显示
            cb.label.lineBreakMode = NSLineBreakByWordWrapping;//换行模式，与上面的计算保持一致。
            cb.label.frame = CGRectMake(cb.label.frame.origin.x, cb.label.frame.origin.y, cb.label.frame.size.width, labelSize.height);//保持原来Label的位置和宽度，只是改变高度。
            
            cb.label.text = labelStr;
            
            cb.value = [CommonUtil dealNullObject:[subNsd objectForKey:@"id"]];
            // 把按钮设置为单选按钮样式
            cb. style = CheckButtonStyleRadio ;
            
            //处理选中状态及可用状态
            NSInteger isCheck = [CommonUtil dealNullObject:[subNsd objectForKey:@"surveyResultID"]].intValue;
            if(isCheck > 0){//已选中
                cb.checked = YES;
            }
            if(_countNum > 0||_isEnd==0){//已投过票或已结束
                cb.enabled = NO;
            }
            // 加入视图
            [self.mainPanel addSubview :cb];
            // 把单选按钮加入按钮组
            [ rg add :cb];
            // 添加选择事件
            //使用关联函数方式传递参数
             objc_setAssociatedObject(cb, &associatedkey, tempEntity.Id, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
            [cb addTarget:self action:@selector(radioClicked:) forControlEvents:UIControlEventTouchUpInside];
            
            _nextY += 42;//与下一元素的垂直间距为42
        }
    }
}

/**复选框事件*/
-(void)checkBoxClicked:(id)sender{
    CheckButton * cb=( CheckButton *)sender;
    NSString  *surveyItemId =[CommonUtil dealNullObject:objc_getAssociatedObject(cb, &associatedkey)];
    if(cb.enable){
        NSMutableSet *cSubResult;//可变集合
        if([_cResultDic objectForKey:surveyItemId]) {//存在
            cSubResult = [_cResultDic objectForKey:surveyItemId];
        } else {//不存在
            cSubResult = [NSMutableSet setWithCapacity:30];
        }
        if (cb.checked) {//如果选中
            [cSubResult addObject:cb.value];
        }else {
            [cSubResult removeObject:cb.value];
        }
         [_cResultDic setValue:cSubResult forKey:surveyItemId];
    }
}

/**单选框事件*/
-(void)radioClicked:(id)sender{
    CheckButton * cb=( CheckButton *)sender;
    NSString  *surveyItemId =[CommonUtil dealNullObject:objc_getAssociatedObject(cb, &associatedkey)];
    if(cb.enable){
        if (cb.checked) {//如果选中
            [_rResultDic setValue:cb.value forKey:surveyItemId];
        }else {
            [_rResultDic removeObjectForKey:surveyItemId];
        }
    }
}
/**
 *创建提交按钮
 *@param btnType 创建的按钮类型：post提交按钮；end结束
 */
- (void)createBtn:(NSString *)btnType{
     int height = iPhone5 ? 0 : 88 ;
    //生成底部按扭-提交
    if ([btnType isEqualToString:@"post"]) {
        UIButton *postBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,460 - height, 320, 44)];
        [postBtn setBackgroundImage:[UIImage imageNamed:@"btnImage.png"] forState:0];
        [postBtn setTitle:@"提交" forState:0];
        [postBtn addTarget:self action:@selector(postResult:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:postBtn];
    }else{//生成底部按扭－已结束
        UIButton *endBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 460 - height, 320, 44)];
        [endBtn setBackgroundImage:[UIImage imageNamed:@"black_line.jpg"] forState:0];
        [endBtn setTitle:@"已结束" forState:0];
        [endBtn addTarget:self action:@selector(endResult:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:endBtn];
    }
   
    _nextY+=50;
}

/**提交调查／投票结果*/
- (void)postResult:(id) sender{
    int i=1;
    //迭代判断是否均已选择
    for(NSDictionary *nsd in _jsonData){
        NSInteger isMulti = [CommonUtil dealNullObject:[nsd objectForKey:@"isMulti"]].intValue;
        if(isMulti==0){
            if(![_cResultDic objectForKey:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]]]){
                NSString *tipStr = [NSString stringWithFormat:@"请选择第 %d 题",i];
                [self.view makeToast:tipStr duration:2.0 position:@"center"];
                return;
            }
        }else{
            if(![_rResultDic objectForKey:[CommonUtil dealNullObject:[nsd objectForKey:@"id"]]]){
                NSString *tipStr = [NSString stringWithFormat:@"请选择第 %d 题",i];
                [self.view makeToast:tipStr duration:2.0 position:@"center"];
                return;
            }
        }
        i++;
    }
    //进行提交
    [self startLoadingViewWithText:@"正在提交..."];
    MKNetworkEngine *currentEngine = [[MKNetworkEngine alloc] initWithHostName:SERVER_URL_SURVEY_POST customHeaderFields:nil];
    MKNetworkOperation *op = [currentEngine operationWithPath:@"" params:[NSDictionary dictionaryWithObject:[self toJsonParams] forKey:@"jsonString"] httpMethod:@"POST"];
    [op addCompletionHandler:^(MKNetworkOperation *completedOperation) {
        //关闭提示加载框
        [self stopLoadingView];
        NSDictionary *json = [completedOperation responseJSON];
        NSString *tipStr = [CommonUtil dealNullObject:[json objectForKey:@"message"]];
        tipStr = [tipStr equals:@""]?@"报名成功":tipStr;
        [self.view makeToast:tipStr duration:2.0 position:@"center"];
        
        
        SurveyMasterEntity *item = [_config objectForKey:@"dataItem"];
        item.countNum = @"1";
        
        [self.navigationController popViewControllerAnimated:YES];
    } errorHandler:^(MKNetworkOperation *completedOperation, NSError *error) {
        //关闭提示加载框
        [self stopLoadingView];
        [self.view makeToast:@"提交失败，请重新登录再操作" duration:2.0 position:@"center"];
    }];
    [currentEngine enqueueOperation:op];
}

/**格式化参数集合*/
- (NSString *)toJsonParams{
    NSMutableArray *tempArray = [NSMutableArray array];
    NSMutableDictionary *tempCell;
    //单选结果
    if ([_rResultDic count]>0) {
        for(NSString *key in _rResultDic.allKeys){
            tempCell = [NSMutableDictionary dictionary];
            [tempCell setValue:key forKey:@"key"];
            [tempCell setValue:[_rResultDic objectForKey:key] forKey:@"value"];
            [tempArray addObject:tempCell];
        }
    }
    //复选结果
    if ([_cResultDic count]>0) {
        NSMutableSet *tempSet;
        NSString *tempStr;
        int tempI = 0;
        for(NSString *key in _cResultDic.allKeys){
            tempCell= [NSMutableDictionary dictionary];
            
            tempSet = [_cResultDic objectForKey:key];
            if (tempSet && [tempSet count]>0) {
                tempI = 0;
                for (NSString *object in tempSet) {
                    if (tempI == 0) {
                        tempStr = object;
                    }else{
                        tempStr = [[CommonUtil dealNullObject:tempStr]  stringByAppendingString:@","];
                        tempStr = [tempStr stringByAppendingString: [CommonUtil dealNullObject:object]];
                    }
                    tempI++;
                }
                [tempCell setValue:key forKey:@"key"];
                [tempCell setValue:tempStr forKey:@"value"];
               [tempArray addObject:tempCell];
            }
        }
    }
    
    NSMutableDictionary *subParams = [NSMutableDictionary dictionary];
    UserInfoService *userInfo=[UserInfoService getUserInfoService];
    [subParams setValue:userInfo.userInfo.Id forKey:@"userId"];
    [subParams setValue:userInfo.userInfo.userName forKey:@"userName"];
    [subParams setValue:_masterId forKey:@"topId"];
    [subParams setValue:tempArray forKey:@"list"];
    
    //转换为json格式字符串
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:subParams options:(NSJSONWritingOptions)0 error:nil];
    NSString *json = [[NSString alloc] initWithBytes:[jsonData bytes] length:jsonData.length encoding:NSUTF8StringEncoding];

    return json;
}

/**提示已结束*/
- (void)endResult:(id) sender{
    [self.view makeToast:@"此次调查已结束，谢谢您的参与" duration:2.0 position:@"center"];
}

- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
